package com.woniuxy.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;

/**
 * @Author: 曾令忠
 * @Description:
 * @Date: 2020/7/10 0010-上午 9:41
 */
public class JwtUtil {
    public static final String SECRET_KEY = "123456";	//秘钥
    public static final long TOKEN_EXPRE_TIME = 1000*6;	//token的过期时间
    public static final long REFRESH_TOKEN_EXPRE_TIME = 1000*60*60*24;	//refreshtoken的过期时间
    public static final String ISSUSER = "zlz";	//

    //生成token
    public static String createToken(String uname){
        Date date = new Date();
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);//指定算法生成token
        return JWT.create()
                .withIssuer(ISSUSER)
                .withIssuedAt(date) //指定签发时间
                .withExpiresAt(new Date(date.getTime()+TOKEN_EXPRE_TIME))//指定token的过期时间
                .withClaim("uname",uname) //用户的账号
                .sign(algorithm);


    }
    //校验token
    public static boolean validate(String token) {
        try {
            //生成加密算法对象
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
            //生成校验器
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUSER)
                    .build();
            verifier.verify(token);
            //合法
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    //从token中提取uname
    public static String getUname(String token) {
        try {
            return JWT.decode(token).getClaim("uname").asString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String token = createToken("张三");
        System.out.println(getUname(token));
        try {
            Thread.sleep(7000);
            System.out.println(validate(token));
            System.out.println(getUname(token));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
